package com.woniuxy.demo;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * @Author: 马宇航
 * @Description: 消费者
 * @DateTime: 22/10/19/0019 14:30
 * @Component: 成都蜗牛学苑
 **/
public class Consumer {
    public static final String QUEUE_NAME="myFirstQueue";
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();
        //信道绑定队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        //重写默认消费者，打印接收到的消息
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String acceptedValue = new String(body, "UTF-8");
                System.out.println("接收到的数据是："+acceptedValue);
            }
        };
        //绑定 队列 与 消费者
        channel.basicConsume(QUEUE_NAME,true,defaultConsumer);
        Thread.sleep(3000);
        //channel关闭
        channel.close();
        //connection关闭
        connection.close();
    }
}
